//
//  273_单向链表的翻转.swift
//  Swift-LeetCode
//
//  Created by 卢悦明 on 2024/1/18.
//

import UIKit

class ReverseList: NSObject {
    static func QA() {
        
        var link = LinkedList<Int>();
        let head = link.creatList(array: [1, 2, 3, 4, 5])
        LinkedList.printList(head)
        
        let qa = ReverseList()
        let newHead = qa.reverseList2(head)
        LinkedList.printList(newHead)
    }
    
    // 206 单向链表的翻转（递归）
    func reverseList1(_ head: ListNode<Int>?) -> ListNode<Int>? {
        guard let _ = head?.next else {
            return head
        }
        let newHead = reverseList1(head?.next)
        let temp = head?.next
        temp?.next = head
        head?.next = nil
        return newHead
    }
    // 206 单向链表的翻转 (迭代)
    func reverseList2(_ head: ListNode<Int>?) -> ListNode<Int>? {
        var head = head
        var newHead: ListNode<Int>?
        while head != nil {
            let temp = head?.next
            head?.next = newHead
            newHead = head
            head = temp
        }
        return newHead
    }
}
